package com.hinnotek.warehouse.ui

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.view.*
import android.widget.*
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.hinnotek.warehouse.R
import com.hinnotek.warehouse.databinding.ActivityScanBinding
import com.hinnotek.warehouse.utils.WAREHOUSE_TYPE_1
import com.hinnotek.warehouse.utils.WAREHOUSE_TYPE_2
import com.hinnotek.warehouse.utils.WAREHOUSE_TYPE_3
import com.hinnotek.warehouse.utils.WAREHOUSE_TYPE_4
import com.hinnotek.warehouse.viewmodel.ScanAddModel
import com.king.zxing.CaptureHelper
import com.king.zxing.OnCaptureCallback
import com.king.zxing.ViewfinderView
import com.lee.common.base.BaseActivity
import com.lee.common.event.MessageEvent
import com.lee.common.event.RESTART_SCAN
import com.lee.common.observer.DefaultObserver
import com.lee.common.utils.ACTIVITY_WAREHOUSE_QRCODE_SCAN
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = ACTIVITY_WAREHOUSE_QRCODE_SCAN)
@AndroidEntryPoint
class QRCodeScanActivity : BaseActivity<ActivityScanBinding>(), OnCaptureCallback {

    private var mCaptureHelper: CaptureHelper? = null
    private val viewModel by viewModels<ScanAddModel>()
    private var applyType = "01"
    private var isSuccess = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scan)
        setTitleBarGone()
        bindingView.vm = viewModel
        bindingView.executePendingBindings()
        viewModel.attachLoading(loadingState)
        viewModel.dialogMsg.observe(this, DefaultObserver(this))

        viewModel.wareId = intent.getIntExtra("wareId", 0)
        viewModel.applyDeviceId = intent.getIntExtra("applyDeviceId", 0)
        applyType = intent.getStringExtra("applyType") ?: "01"
        registerEvent(this@QRCodeScanActivity)
    }

    override fun initVew() {
        bindingView.ivFlash.visibility = View.INVISIBLE
        bindingView.ivLeft.setOnClickListener { this@QRCodeScanActivity.finish() }
        val surfaceView = bindingView.surfaceView
        val viewfinderView: ViewfinderView = bindingView.viewfinderView
        mCaptureHelper =
            CaptureHelper(this@QRCodeScanActivity, surfaceView, viewfinderView, bindingView.ivFlash)
        mCaptureHelper?.setOnCaptureCallback(this)
        mCaptureHelper?.onCreate()
        mCaptureHelper!!.vibrate(true)
            .fullScreenScan(true) //全屏扫码
            .supportVerticalCode(true) //支持扫垂直条码，建议有此需求时才使用。
            .supportLuminanceInvert(true) //是否支持识别反色码（黑白反色的码），增加识别率
            .continuousScan(false)
            .playBeep(true)
        checkPermission()
    }


    /**
     * 二维码扫描回调
     */
    override fun onResultCallback(result: String): Boolean {
        viewModel.productNum = getUrlList(result)["num"] ?: ""
        when (applyType) {
            WAREHOUSE_TYPE_1 -> {
                viewModel.loadData1()
            }
            WAREHOUSE_TYPE_2 -> {
                viewModel.loadData2()
            }
            WAREHOUSE_TYPE_3 -> {
                viewModel.loadData3()
            }
            WAREHOUSE_TYPE_4 -> {
                viewModel.loadData4()
            }
        }
        return true
    }

    override fun setData() {
        //入库
        viewModel.stockInData.observe(this, Observer {
            handleScanData(viewModel.isSuccess)
        })
        //出库
        viewModel.stockOutOfData.observe(this, Observer {
            handleScanData(viewModel.isSuccess)
        })
        //借用
        viewModel.borrowApplyData.observe(this, Observer {
            handleScanData(viewModel.isSuccess)
        })
        //报损
        viewModel.lossReportData.observe(this, Observer {
            handleScanData(viewModel.isSuccess)
        })
    }

    private fun handleScanData(isSuccess: Boolean) {
        if (isSuccess) {
            setResult(200)
            this.isSuccess = true
            Toast.makeText(this, "扫描成功", Toast.LENGTH_SHORT).show()
            handler.postDelayed(
                {
                    mCaptureHelper?.restartPreviewAndDecode()
                }, 1000
            )
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun bindWxMessageEvent(event: MessageEvent) {
        if (event.message == RESTART_SCAN) {
            mCaptureHelper?.restartPreviewAndDecode()
        }
    }

    //权限申请返回
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        if (requestCode == REQUEST_CODE_ASK_PERMISSIONS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (mCaptureHelper != null) {  //成功
                    //mCaptureHelper.onResume();
                }
            } else {
                // Permission Denied 拒绝
                Toast.makeText(this, "获取权限失败，无法扫描", Toast.LENGTH_SHORT).show()
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun onPointerCaptureChanged(hasCapture: Boolean) {}
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (mCaptureHelper != null) mCaptureHelper?.onTouchEvent(event)
        return super.onTouchEvent(event)
    }

    /**
     * 权限检查
     */
    private fun checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val enablePhoneState =
                (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                        == PackageManager.PERMISSION_GRANTED)
            if (!enablePhoneState) {
                requestPermissions(
                    arrayOf(Manifest.permission.CAMERA),
                    REQUEST_CODE_ASK_PERMISSIONS
                )
            }
        }
    }

    companion object {
        const val REQUEST_CODE_ASK_PERMISSIONS = 3
    }

    override fun onPause() {
        if (mCaptureHelper != null) mCaptureHelper?.onPause()
        super.onPause()
    }

    override fun onResume() {
        if (mCaptureHelper != null) mCaptureHelper?.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        if (mCaptureHelper != null) mCaptureHelper?.onDestroy()
        destroyEvent(this@QRCodeScanActivity)
        super.onDestroy()
    }

    /**
     * 获取url参数
     */
    private fun getUrlList(url: String): Map<String, String> {
        val index = url.indexOf("?");
        val temp = url.substring(index + 1);
        val keyValue = temp.split("&");
        val result = HashMap<String, String>();
        for (index in keyValue.indices) {
            val list = keyValue[index].split("=");
            result.put(list[0], list[1]);
        }
        return result;
    }

}